package com.example.security.config;

import com.example.security.exception.ServiceImplException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import oj.common.core.domain.Result;
import oj.common.core.enums.ResultCode;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler<T> {
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<?>
    handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                        HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不⽀持'{}'请求", requestURI, e.getMethod());
        return Result.failed(ResultCode.FAILED_USER_NOT_EXISTS);
    }
    /**
     * 拦截运⾏时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<?> handleRuntimeException(RuntimeException e, HttpServletRequest
            request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发⽣异常.", requestURI, e);
        return Result.failed(ResultCode.ERROR);
    }

    /**
     * 捕获service层的异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(ServiceImplException.class)
    public Result<?> ServiceImplException(ServiceImplException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        ResultCode resultCode = e.getResultCode();
        log.error("请求地址'{}',发生业务异常.", requestURI, resultCode.getMsg(),e);
        return Result.failed(resultCode);
    }
    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发⽣异常.", requestURI, e);
        return Result.failed (ResultCode. ERROR );
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleBindException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发⽣异常.", requestURI, e);
        return Result.failed (ResultCode.ERROR_FORMAT );
    }
}
